/**
 * Copyright (c) 2007-2008 Nearchos Paspallis
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/**
 * AspectSense
 *
 * Middleware for annotation-based, context-aware and adaptive services for
 * mobile and ubiquitous computing
 *
 * This project is an open-source effort, initiated by Nearchos Paspallis as
 * part of his PhD work at the University of Cyprus (http://www.ucy.ac.cy).
 *
 * More information about the project is available at "http://aspectsense.org".
 */

package org.aspectsense.context;

import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @author Nearchos Paspallis [nearchos@cs.ucy.ac.cy]
 *         Date: Jan 11, 2008
 *         Time: 10:18:57 AM
 */
public class DefaultContextModel implements ContextModel
{
    private final Map<ContextType, Set<ContextType>> childrenMap;

    public static final String [] DEFAULT_CONTEXT_TYPES = {
            DefaultContextType.USER_PREFERENCES_CONTEXT_TYPE.getType(),
            "context.user.handsfree-required",
            "context.infrastructure",
            // changes when components are installed, uninstalled, or updated
            DefaultContextType.COMPONENT_AVAILABILITY_CONTEXT_TYPE.getType(),
            // changes when distributed instances of services are discovered or gone
            DefaultContextType.SERVICE_AVAILABILITY_CONTEXT_TYPE.getType(),
            "context.infrastructure.network",
            "context.infrastructure.memory-availability",
            "context.infrastructure.cpu-availability",
            "context.environment",
            "context.environment.location",
            "context.environment.weather",
            "context.environment.weather.temperature",
            "context.environment.weather.humidity",
            "context.environment.light",
            "context.environment.light.brightness_level",
            "context.environment.sound",
            "context.environment.sound.noise_level"
    };

    public DefaultContextModel()
    {
        super();

        childrenMap = new HashMap<ContextType, Set<ContextType>>();

        // instantiate the model
        for(final String contextType : DEFAULT_CONTEXT_TYPES)
        {
            addContextType(DefaultContextType.getContextType(contextType));
        }
    }

    private void addContextType(final ContextType contextType)
    {
        // assume that no children of the given contextType are already added!
        final ContextType parentContextType = getParentContextType(contextType);
        Set<ContextType> childContextTypes = childrenMap.get(parentContextType);

        if(childContextTypes == null)
        {
            childContextTypes = new HashSet<ContextType>();
            childrenMap.put(parentContextType, childContextTypes);
        }

        childContextTypes.add(contextType);
    }

    public ContextType [] getAllContextTypes()
    {
        return getChildContextTypes(DefaultContextType.ROOT_CONTEXT_TYPE);
    }

    public ContextType getContextType(String type)
    {
        return DefaultContextType.getContextType(type);
    }

    public ContextType getParentContextType(final ContextType contextType)
    {
        if(contextType == null)
        {
            throw new NullPointerException("Illegal null argument");
        }

        if(contextType == DefaultContextType.ROOT_CONTEXT_TYPE)
        {
            return null;
        }

        final String type = contextType.getType();

        final int lastDotIndex = type.lastIndexOf('.');

        final ContextType parentContextType
                = DefaultContextType.getContextType(type.substring(0, lastDotIndex));

        assert childrenMap.get(parentContextType).contains(contextType);

        return parentContextType;
    }

    public ContextType [] getChildContextTypes(final ContextType contextType)
    {
        final ContextType [] allContextTypes = new ContextType[childrenMap.size()];

        final Queue<ContextType> queue = new LinkedBlockingQueue<ContextType>();
        queue.add(contextType);

        int count = 0;
        while (!queue.isEmpty())
        {
            final ContextType currentContextType = queue.remove();

            allContextTypes[count++] = currentContextType;

            final Set<ContextType> childrenContextTypes
                    = childrenMap.get(currentContextType);
            for(final ContextType childContextType : childrenContextTypes)
            {
                queue.add(childContextType);
            }
        }

        return allContextTypes;
    }
}